package service

import (
	"gitee.com/csingo/cLog"
	"github.com/gin-gonic/gin"
	"satis-go/app/collector/model"
	"satis-go/base/collector"
	"strings"
)

type PackagesService struct {
	collector.PackagesServiceHTTPServer
}

func (i *PackagesService) Add(ctx *gin.Context, req *collector.PackagesServiceAddReq) (rsp *collector.PackagesServiceAddRsp, err error) {
	pkg := &model.Packages{
		ID:        req.Id,
		IncludeId: req.IncludeId,
		Name:      strings.Trim(req.Name, " "),
		State:     0,
		Type:      req.Type,
		Url:       strings.Trim(req.Url, " "),
		Version:   req.Version,
	}

	rsp = &collector.PackagesServiceAddRsp{}
	m := &model.Packages{}
	rsp.Data, err = m.Save(ctx, pkg)

	return
}

func (i *PackagesService) Del(ctx *gin.Context, req *collector.PackagesServiceDelReq) (rsp *collector.PackagesServiceDelRsp, err error) {
	pkgModel := &model.Packages{}
	verModel := &model.Versions{}

	err = pkgModel.DelById(ctx, req.Id)
	if err != nil {
		return
	}

	err = verModel.DelByPackageId(ctx, req.Id)

	return
}

func (i *PackagesService) AllByInclude(ctx *gin.Context, req *collector.PackagesServiceAllByIncludeReq) (rsp *collector.PackagesServiceAllByIncludeRsp, err error) {
	rsp = &collector.PackagesServiceAllByIncludeRsp{}
	pkgs, err := (&model.Packages{}).FindByIncludeId(ctx, req.IncludeId)
	if err != nil {
		cLog.WithContext(ctx, map[string]interface{}{
			"req": req,
			"err": err.Error(),
		}).Error("PackagesService.AllByInclude:获取包异常")
		return nil, err
	}

	pkgIds := []uint64{}
	for _, pkg := range pkgs {
		pkgIds = append(pkgIds, pkg.ID)
	}

	vers, err := (&model.Versions{}).FindByPackageIds(ctx, pkgIds)
	if err != nil {
		cLog.WithContext(ctx, map[string]interface{}{
			"req": req,
			"err": err.Error(),
		}).Error("PackagesService.AllByInclude:获取版本异常")
		return nil, err
	}

	pkgVers := map[uint64][]*model.Versions{}
	for _, ver := range vers {
		if _, ok := pkgVers[ver.PackageId]; !ok {
			pkgVers[ver.PackageId] = []*model.Versions{}
		}
		pkgVers[ver.PackageId] = append(pkgVers[ver.PackageId], ver)
	}

	versions := map[uint64]interface{}{}
	for pkgid, ver := range pkgVers {
		versions[pkgid] = ver
	}

	rsp.Packages = pkgs
	rsp.Versions = versions

	return
}
